const express = require("express");
const crypto = require("crypto");
const {v4} =require('uuid')
const UserCountTables=require('../db/UserCountDB/UserTable')
const UserDetailTables=require('../db/UserDetailDB/UserDetailTable')
const BlogTables =require('../db/BlogDataDB/BlogTable')
//加密
function enCryptData(data,key,algorithm){
    if (!crypto.getHashes().includes(algorithm)){
        throw new Error("不支持次哈希函数")
    }
    //创建加密对象
    let cryobj=crypto.createHash(algorithm,key)
    cryobj.update(data)
    return cryobj.digest("hex")

}



const authenticationApp = express()


authenticationApp.post('/registerUser',function (req,res){
    //注册接口
    let key=v4()
    let password=enCryptData(req.body.password,key,'sha256')
    let userName = req.body.userName
    let avatar = req.body.avatar
    let token =enCryptData(v4(),v4(),'sha256')

    //查询表
    UserCountTables.find({
        userName: userName
    }).then(rs=>{
        if (rs.length){
            res.send({
                status:500,
                message:"该用户已注册"
            })
        }else {
            UserCountTables.create({
                userName,
                password,
                key,
                avatar,
                token,
                isAdmin:false,
                introduction:"",
                approved:false,
                createTime:new Date()

            }).then(rs=>{
                //投放token
                res.setHeader('Authorization',token)
                res.send({
                    status:200,
                    message:"该账号正在审核中"
                })
            })

            UserDetailTables.create({
                key,
                articles:[],
                comments:[],
                likes:[],
                attentions:[],
                blacklist:[],
            })

        }
    })

})

authenticationApp.get('/checkPermission',function (req,res){

    UserCountTables.find({
        token:req.headers.authorization
    }).then(async rs=>{
        if (rs.length){

            //返回用户的信息
            let userDetail={}
            await UserDetailTables.find({
                key:rs[0].key
            },{
                key:false,
                _id:false,
                __v:false
            }).then(rsuerdetail=>{
                userDetail=rsuerdetail[0]
            })

            //返回views
            let views=0
            let likes=0
            //文章表寻找
            await BlogTables.find({
                'author.userName': rs[0].userName
            }).then(blogList => {
                blogList.forEach(blogData => {
                    // console.log(blogData)
                    views += blogData.views;
                    likes += blogData.likes;
                })
            })

            res.send({
                status:200,
                message:"鉴权成功",
                data:{
                    userData:{
                        //用户信息
                        userName:rs[0].userName,
                        avatar:rs[0].avatar,
                        introduction:rs[0].introduction,
                        isAdmin:rs[0].isAdmin,
                        //用户关注信息
                        userDetail,
                        views:views,//你的文有多少人看过
                        likes:likes//你的文章有多人喜欢
                    }
                }
            })
        }else {
            res.send({
                status:500,
                message:"鉴权失败"
            })
        }
    })




})


authenticationApp.post('/loginUser',function (req,res){
    let userName = req.body.userName

    UserCountTables.find({
        userName:userName
    }).then(rs=>{
        if (rs.length){
            if (rs[0].password === enCryptData(req.body.password,rs[0].key,'sha256')){
                //判断用户是否过审核
                console.log(rs[0].approved)
                if (rs[0].approved){
                    res.setHeader('Authorization',rs[0].token)
                    res.send({
                        status:200,
                        message:"登陆成功"
                    })
                }else {
                    res.send({
                        status:500,
                        message:"该账号正在审核中"
                    })
                }

            }else {
                res.send({
                    status:500,
                    message:"用户名密码错误"
                })
            }


        }else {
            res.send({
                status:500,
                message:"该用户未找到"
            })
        }

    })

})

authenticationApp.post('/updateUserInfo', function (req, res) {
    UserCountTables.updateOne({
        token: req.headers.authorization
    }, {
        $set: {
            avatar: req.body.avatar,
            introduction: req.body.introduction
        }
    }).then(async rs => {
        res.send({
            status: 200,
            message: '用户信息更新成功'
        })
    })
})

authenticationApp.get("/unapprovedUser",function (req,res){
    //发讯所有没过审核的数据
    UserCountTables.find({
        token:req.headers.authorization
    }).then(async rs=>{
        //判断是否是管理员  反爬虫
        if (rs.length &&rs[0].isAdmin){
        //     擦讯总数
            let {offset, limit} = req.query; // 获取参数
            let totalNum = 0;
            await UserCountTables.find({
                approved: false
            }).then(unapprovedUsers=>{
                totalNum = unapprovedUsers.length; // 获取未授权用户的总数
            })
            UserCountTables.find({
                approved: false
            },{
                _id: false,
                __v: false
            },{
                skip: Number(offset),
                limit: Number(limit)
            }).then(unapprovedUsers=>{
                res.send({
                    status: 200,
                    message: '查询成功',
                    data: {
                        userTotalNum:totalNum,
                        userList: unapprovedUsers
                    }
                })
            })

        }else {
            res.send({
                status:401,
                message:"无权限"
            })
        }
    })


})

//获取所有的用户信息
authenticationApp.get("/unAllUser",function (req,res){
    //发讯所有没过审核的数据
    UserCountTables.find({
        token:req.headers.authorization
    }).then(async rs=>{
        //判断是否是管理员  反爬虫
        if (rs.length &&rs[0].isAdmin){
            //     擦讯总数
            let {offset, limit} = req.query; // 获取参数
            let totalNum = 0;
            await UserCountTables.find({}).then(unapprovedUsers=>{
                totalNum = unapprovedUsers.length; // 获取未授权用户的总数
            })
            UserCountTables.find({},{
                _id: false,
                __v: false
            },{
                skip: Number(offset),
                limit: Number(limit)
            }).then(userList=>{
                res.send({
                    status: 200,
                    message: '查询成功',
                    data: {
                        userTotalNum:totalNum,
                        userList: userList
                    }
                })
            })

        }else {
            res.send({
                status:401,
                message:"无权限"
            })
        }
    })
})

/*
* 在axios中 post 直接{}  get params
* 在vue中    params是路由:key
* 在node   get query post body 路由 params
* */
// 同意
authenticationApp.post("/approvedUser",function (req,res){
    //把approve 设置true
    UserCountTables.find({
        token:req.headers.authorization//
    }).then(rs=>{
        if (rs.length && rs[0].isAdmin){
            //修改
            UserCountTables.updateOne({
                key:req.body.key
            },{
                $set:{
                    approved: true
                }
            }).then(()=>{
                res.send({
                    status: 200,
                    message: '批准用户注册'
                })
            })
        }else{
            res.send({
                status: 401,
                message: '没有操作权限'
            })
        }
    })

})

authenticationApp.post('/unApprovedUser', function (req,res){
    UserCountTables.find({
        token: req.headers.authorization
    }).then(async (rs)=>{
        if (rs.length && rs[0].isAdmin){
            UserCountTables.updateOne({
                key: req.body.key
            },{
                $set:{
                    approved: false
                }
            }).then(()=>{
                res.send({
                    status: 200,
                    message: '取消用户注册'
                })
            })
        }else{
            res.send({
                status: 401,
                message: '没有操作权限'
            })
        }
    })
})
//删除
authenticationApp.post("/deleteUser",function (req,res){
    UserCountTables.find({
        token:req.headers.authorization
    }).then(async rs=>{
        if (rs.length && rs[0].isAdmin){
            //删除博客
            await UserCountTables.find({
                key: req.body.key
            }).then(rs=>{
                //删除博客数据
                BlogTables.deleteMany({
                    'author.userName':rs[0].userName
                }).then(()=>{
                    console.log('删除用户的博客数据')
                })
            })

            await UserDetailTables.deleteOne({
                key: req.body.key
            }).then(()=>{
                console.log('删除用户的详细数据')
            })

            await UserCountTables.deleteOne({
                key: req.body.key
            }).then(()=>{
                console.log('删除用户的主数据')
            })

            res.send({
                status: 200,
                message: '删除用户成功'
            })

        }else {
            res.send({
                status:401,
                message:"无权限"
            })
        }
    })


})

authenticationApp.post('/setAdmin', function (req, res){
    UserCountTables.find({
        token: req.headers.authorization
    }).then((rs)=>{
        if (rs.length && rs[0].isAdmin){
            UserCountTables.updateOne({
                key: req.body.key
            }, {
                $set: {
                    isAdmin: true
                }
            }).then(userInfos => {
                res.send({
                    status: 200,
                    message: '更改用户权限成功'
                })
            })
        }else{
            res.send({
                status: 401,
                message: '没有操作权限'
            })
        }
    })
})

authenticationApp.post('/cancelAdmin', function (req, res){
    UserCountTables.find({
        token: req.headers.authorization
    }).then((rs)=>{
        if (rs.length && rs[0].isAdmin){
            UserCountTables.updateOne({
                key: req.body.key
            }, {
                $set: {
                    isAdmin: false
                }
            }).then(userInfos => {
                res.send({
                    status: 200,
                    message: '更改用户权限成功'
                })
            })
        }else{
            res.send({
                status: 401,
                message: '没有操作权限'
            })
        }
    })
})


//查询用户
authenticationApp.get('/userReginsterInfo',function (req,res){
    UserCountTables.find({
        token: req.headers.authorization
    }).then((rs)=>{
        if (rs.length && rs[0].isAdmin){
            UserCountTables.find({}, {
                createTime:true
            }).then(userInfo => {
                res.send({
                    status: 200,
                    message: '查询成功',
                    data:{
                        userInfo
                    }
                })
            })
        }else{
            res.send({
                status: 401,
                message: '没有操作权限'
            })
        }
    })


})

module.exports ={
    authenticationApp
}